import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
import LoginView from '@/views/LoginView.vue';
import ProfileView from '@/views/ProfileView.vue';
import AccountSettings from '../views/AccountSettings.vue';
import ChatInterface from '../views/ChatInterface.vue';

// 路由规则
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/profile',
    name: 'Profile',
    component: ProfileView
  },
  {
    path: '/accountsettings',
    name: 'AccountSettings',
    component: AccountSettings
  },
  {
    path: '/chat-interface',
    name: 'ChatInterface',
    component: ChatInterface
  },
  {
    path: '/',
    redirect: '/login'
  },
  // 404页面重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局前置守卫：控制登录权限
router.beforeEach((to, from, next) => {
  // 不需要登录的页面（白名单）
  const whiteList = ['Login'];
  const isWhiteList = whiteList.includes(to.name);
  
  // 获取token
  const hasToken = !!localStorage.getItem('userToken');

  if (isWhiteList) {
    // 白名单页面直接放行
    next();
  } else {
    // 非白名单页面：有token则放行，无token则跳登录
    hasToken ? next() : next('/login');
  }
});

export default router;
    